//
//  APPLEEmoticonCollectionViewCell.swift
//  123
//
//  Created by pangjiaxing on 16/1/13.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
private let pageControlBottomMargin:CGFloat = 20
private let pageControlLeftAndRightMargin:CGFloat = 10
class APPLEEmoticonCollectionViewCell: UICollectionViewCell {
    
    private lazy var recentlabel : UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontsize: 12)
        label.text = "最近表情"
        return label
    }()
    
    private lazy var deleteButton : UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        return button
    }()
    
    private lazy var popView :APPLEPopView = APPLEPopView.popView()
    
    lazy var emoticonButtons: [APPLEEmoticonButton] = [APPLEEmoticonButton]()
    
    
    var indexPath:NSIndexPath? {
        didSet{
            recentlabel.hidden = indexPath?.section != 0
        }
    }
    
    var emoticon : [APPLEEmoticon]?{
        
        didSet{
            
            for value in emoticonButtons {
                value.hidden = true
            }
            
            for (i,value) in (emoticon?.enumerate())! {
                let button = emoticonButtons[i]
                button.hidden = false
                button.emoticon = value
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
//        contentView.addSubview(testlabel)
        for _ in 0..<HMEmoticonKeyboardCountOfPage {
            let button = APPLEEmoticonButton ()
            button.addTarget(self, action: "didClickButton:", forControlEvents: .TouchUpInside)
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            contentView.addSubview(button)
            contentView.addSubview(recentlabel)
            emoticonButtons.append(button)
            contentView.addSubview(deleteButton)
        }
//        testlabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView)
//        }
        recentlabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-5)
        }
        
        let ges = UILongPressGestureRecognizer(target: self, action: "longPress:")
        addGestureRecognizer(ges)
    }
    
    @objc private func didClickButton(button:APPLEEmoticonButton){
        
        // 发送表情选中的通知
        NSNotificationCenter.defaultCenter().postNotificationName(HMEmoticonDidSelectedNotification, object: nil, userInfo: ["emoticon":button.emoticon!])
        
        let emotion = button.emoticon
        let pop = APPLEPopView.popView()
        pop.emoticon = emotion
        let window = UIApplication.sharedApplication().windows.last!
        let rect = button.superview?.convertRect(button.frame, toView: window)
        pop.center.x = CGRectGetMidX(rect!)
        pop.frame.origin.y = CGRectGetMaxY(rect!) - pop.frame.size.height
        window.addSubview(pop)
        
        // 0.25 秒之后移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            pop.removeFromSuperview()
        }
    }
    
    @objc private func longPress(ges:UIGestureRecognizer){
        func buttonWithLocation(location:CGPoint) ->APPLEEmoticonButton?{
            
            for  button in emoticonButtons {
                if CGRectContainsPoint(button.frame, location){
                return button
                }
            }
            return nil
            
        }
        
        let location = ges.locationInView(self)
        
        guard let button = buttonWithLocation(location) else{
            return
        }
        
        let state = ges.state
        
        switch state {
        case .Began,.Changed:
            let window = UIApplication.sharedApplication().windows.last
            let rect = button.superview?.convertRect(button.frame, toView: window)
            popView.center.x = CGRectGetMidX(rect!)
            popView.frame.origin.y = CGRectGetMaxY(rect!) - popView.frame.size.height
            window!.addSubview(popView)
            popView.emoticon = button.emoticon
        case.Ended,.Cancelled:
            popView.removeFromSuperview()
        default:
            popView.removeFromSuperview()
        }
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 调整20个按钮的位置
        
        let itemW = (self.frame.width-pageControlLeftAndRightMargin) / CGFloat(HMEmoticonKeyboardPageMaxCol)
        let itemH =  (self.frame.height-pageControlBottomMargin) / CGFloat(HMEmoticonKeyboardPageMaxRow)
        
        for (i,value) in emoticonButtons.enumerate() {
            
            // 计算 button 行数与列数
            let col = i % HMEmoticonKeyboardPageMaxCol
            let row = i / HMEmoticonKeyboardPageMaxCol
            
            value.frame.origin.x = CGFloat(col) * itemW+pageControlLeftAndRightMargin*0.5
            value.frame.origin.y = CGFloat(row) * itemH
            value.frame.size = CGSize(width: itemW, height: itemH)
            
        }
        
        // 调整删除按钮的位置
        deleteButton.frame = CGRect(x: self.frame.width - itemW-pageControlLeftAndRightMargin*0.5, y: self.frame.height - itemH-pageControlBottomMargin, width: itemW, height: itemH)
    }
    
}
